package edu.zju.gis.cky.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.List;

/**
 * @author Zhou Yuquan
 * @version 1.0, 2021-12-06
 */
@Slf4j
public class FileHelper {

    public static String getName(String path) {
        int index1 = path.lastIndexOf("/");
        int index2 = path.lastIndexOf(".");
        return path.substring(index1 + 1, index2);
    }

    public static String getSuffix(String path) {
        int index = path.lastIndexOf(".");
        return path.substring(index + 1);
    }

    public static long getSize(String path) {
        File file = new File(path);
        if (!file.isDirectory()) {
            return file.length();
        } else {
            long count = 0;
            File[] files = file.listFiles();
            if (files != null) {
                for (File file1 : files) {
                    if (file1.isDirectory()) {
                        count += getSize(file1.getPath());
                    } else {
                        count += file1.length();
                    }
                }
            }
            return count;
        }
    }

    public static boolean copy(String fromPath, String toPath) {
        File fromFile = new File(fromPath);
        if (!fromFile.exists()) {
            return false;
        }
        File toFile = new File(toPath);
        File toDir = toFile.getParentFile();
        if (!toDir.exists()) {
            toDir.mkdirs();
        }
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(fromFile), 2048);
            OutputStream out = new FileOutputStream(toFile);
            return streamWrite(in, out);
        } catch (IOException e) {
            log.error(e.getMessage());
            return false;
        }
    }

    public static boolean batchCopy(List<String> fromPaths, List<String> toPaths) {
        if (fromPaths.size() != toPaths.size()) {
            return false;
        }
        for (int i = 0; i < fromPaths.size(); i++) {
            if (!copy(fromPaths.get(i), toPaths.get(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean streamWrite(InputStream in, OutputStream out) {
        try {
            byte[] b = new byte[2048];
            while (in.read(b) != -1) {
                out.write(b);
            }
            return true;
        } catch (IOException e) {
            log.error(e.getMessage());
            return false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }

}
